package com.zan.service.impl;

import com.zan.entity.LoginUser;
import com.zan.entity.User;
import com.zan.service.LoginService;
import com.zan.utils.JwtUtils;
import com.zan.utils.RedisCache;
import com.zan.vo.ResponseResult;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author Zan
 * @Date 2023/10/17 14:35
 * @Description :
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        // AuthenticationManager authenticate 进行用户认证
        // 将登录的用户名和密码封装成UsernamePasswordAuthenticationToken对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken); //这个方法里面会去走UserDetailsServiceImpl
        if (Objects.isNull(authenticate)) {
            // 如果认证没通过，给出响应的提示
            throw new RuntimeException("登录失败");
        } else {
            // 如果认证通过了，使用userId生成一个jwt，jwt存入ResponseResult进行返回
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            Long id = loginUser.getUser().getId();
            String jwt = JwtUtils.createJWT(String.valueOf(id));
            // 把完整的用户信息存入redis，userId作为key  token: jwt
            redisCache.setCacheObject(String.valueOf(id), loginUser);

            Map<String, String> map = new HashMap<>();
            map.put("token", jwt);
            return new ResponseResult(200, "登录成功", map);
        }
    }

    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder中的用户id (这里面的值不需要删除)
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        // 删除redis中的值
        redisCache.deleteObject(String.valueOf(id));
        return new ResponseResult(200, "注销成功");
    }
}
